import Config from '@/global/config';
import Msg from '@/global/utils/msg';
import { article } from '@/global/local-data/blog';

/**
 * 公共函数
 */
export default {
    /**
     *
     * @param {array} menuList 菜单列表
     * @returns {array}
     */
    addRouterAuth(menuList) {
        menuList.sort((a, b) => {
            return a.sort - b.sort;
        });

        let menus = [];

        for (let i in menuList) {
            if (menuList[i].type == 2) {
                const routerUrlArr = menuList[i].path.split('/');
                let routerUrl = undefined;

                // 路由路径
                if (routerUrlArr[1] === '') {
                    routerUrl = menuList[i].path;
                } else {
                    routerUrl = menuList[i].path + '/Index.vue';
                }

                // 页面名
                let name = '';
                for (let j = 0; j < menuList[i].code.length; j++) {
                    if (j === 0) {
                        name = menuList[i].code[j].toUpperCase();
                    } else {
                        name += menuList[i].code[j].toLowerCase();
                    }
                }

                menus.push({
                    path: menuList[i].path,
                    menuName: menuList[i].name,
                    name: name,
                    meta: {
                        auth: []
                    },
                    component: () => this.generateRouter(routerUrl)
                    // component: () => import('@/views' + routerUrl)
                });
            }
        }

        // 写入权限到路由
        const menuData = menuList;
        const menuDatas = menuList;

        for (let i in menus) {
            for (let k in menuData) {
                // 菜单路由URL是否跟路由定义的URL相等
                if (menus[i].path === menuData[k].path) {
                    // 路由URL相等查找有权限的子菜单
                    for (let n in menuDatas) {
                        if (menuData[k].id === menuDatas[n].pid) {
                            menus[i].meta.auth.push(menuDatas[n].code);
                        }
                    }
                }
            }
        }

        return menus;
    },
    /**
     * 动态加载路由
     * @param {*} url 路由url
     * @returns 
     */
    generateRouter(url) {
        return new Promise((resolve, reject) => {
            import(/* webpackChunkName: "[request]" */ '@/views' + url).then(module => {
                resolve(module);
            }).catch(e => {
                reject(new Error('动态加载路由失败'));
            });
        });
    },

    /**
     * 树形菜单数据处理成索引0所有一级分类，索引1所有子类
     * @param {array} categoryData 列表数据
     * @return {array}
     */
    getCategory(categoryData, menuArr = []) {
        categoryData.sort((a, b) => {
            return a.sort - b.sort;
        });
        categoryData.forEach((v) => {
            if (v.pid == 0) {
                (menuArr[0] || (menuArr[0] = [])).push(v);
            } else {
                (menuArr[v.pid] || (menuArr[v.pid] = [])).push(v);
            }
        });

        return menuArr;
    },

    /**
     * 处理children数据结构的菜单数据
     * @param {array} menuData 表格数据
     * @param {array} arr 空数组，用于存值
     * @return {array}
     */
    getChildrenTree(menuData, arr) {
        for (let i in arr) {
            // 如果查找的子类存在就遍历
            let pidArr = menuData[arr[i].id];

            if (pidArr != undefined) {
                for (let j in pidArr) {
                    (arr[i].childrens || (arr[i].childrens = [])).push(pidArr[j]);
                }

                let getChildrens = this.getChildrenTree(menuData, arr[i].childrens);
                arr[i].childrens = getChildrens;
            }
        }

        return arr;
    },

    /**
     * 处理表格数据，用于可以展开分类表格
     * @param {Array} menuData 处理好的children表格数据
     * @param {Array} parent 父数组，默认传NULL
     * @param {int} levelCount 层级统计，默认传NULL
     * @param {Boolean} expandedAll true-全部关闭，flase-全部展开
     * @returns {Array}
     */
    getTreeToArray(menuData, parent, levelCount, expandedAll) {
        let tmp = [];

        menuData.forEach((item) => {
            // 是否展开或关闭全部
            if (item.expanded === undefined) {
                item.expanded = expandedAll;
            }

            // 父对象，默认为NULL
            if (parent) {
                item.parent = parent;
            }

            // 获取层级
            let level = 0;

            if (levelCount !== undefined && levelCount !== null) {
                level = levelCount + 1;
            }

            item.level = level;

            // 放入数组，递归下级分类
            tmp.push(item);

            if (item.childrens && item.childrens.length > 0) {
                let childrens = this.getTreeToArray(item.childrens, item, level, expandedAll);
                tmp = tmp.concat(childrens);
            }
        });

        return tmp;
    },
    /**
     * 验证图片
     * @param {file} file # 文件大小是字节(b)
     * @return {string}
     */
    validateImg(file) {
        // 验证图片格式和大小
        const isFileType = Config.upload.img.type.indexOf(file.type) == -1 ? false : true;
        // 需要把上传图片的size（B）转换成KB 再把配置文件的MB转换成KB
        const isFileSize = file.size / 1024 < Config.upload.img.size * 1024;

        return new Promise((resolve, reject) => {
            if (!isFileType) {
                Msg.error(`只支持${Config.upload.image.typeStr}格式`);
                resolve(false);
            }

            if (!isFileSize) {
                Msg.error(`文件大小不能超过${Config.upload.image.size}MB`);
                resolve(false);
            }

            // 获取base64图片数据
            const reader = new FileReader();
            reader.readAsDataURL(file);

            reader.onload = () => {
                // reader.result;
                resolve(true);
            };
        });
    },
    /**
     * 拼接上传图片路径，适应开发、生产环境
     * @param {file} file
     * @return {file}
     */
    splicingImageUrl(url) {
        if (url == '') {
            return '';
        } else if (url.indexOf('http://') >= 0 || url.indexOf('https://') >= 0) {
            return url;
        } else {
            return Config.baseURL + url;
        }
    },
    /**
     * 处理tabs
     * @param {*} arr
     * @param {*} tabs
     * @returns
     */
    getTabs(arr, tabs = []) {
        article.tabs.forEach((item) => {
            arr.forEach((v) => {
                if (item.status == v.status) {
                    item.value = v.total;
                }
            });

            tabs.push(item);
        });

        return tabs;
    }
};
